import PageModel from "../../../models/Page";
import Crypt from "../../../utils/Crypt";
import config from "../../../config/config";

const pageModel = new PageModel()

Page({
  data: {

    page: 0,
    pageSize: 10,
    list: [],
    busy: false,
    baseUrl: config.app_base_url,

    // 商家ID
    merchant_id: 0

  },

  onShow: function () {
    this.noLogin()
  },

  onLoad: function (options) {
    this._getList()
  },

  onReachBottom() {
    this._getList(true)
  },

  // 没有登录
  noLogin() {
    const merchant_id = wx.getStorageSync('merchant_id')
    if (!merchant_id) {
      wx.navigateTo({
        url: '/sub_main/pages/merchant-login/index'
      })
    }
    this.setData({ merchant_id })
  },

  _getList(append = false) {
    if (this.data.busy === false) {
      this.setData({
        busy: true,
        page: this.data.page + 1
      })
      pageModel.merchantOrder({ ...this.data, merchant_id: wx.getStorageSync('merchant_id') }).then(response => {
        let { data } = response
        data = Crypt.parse(data)
        if (data.list.length === 0) {
          this.setData({ busy: true })
        } else {
          this.setData({ busy: false })
          if (append) {
            this.setData({ list: this.data.list.concat(data.list) })
          } else {
            this.setData({ list: data.list })
          }
        }

        // console.log(this.data.list)

      })
    }
  },

  // 扫码核销
  onScan(e) {
    wx.scanCode({
      // 只让扫二维码
      scanType: ['qrCode'],
      success: (res) => {
        let { result } = res
        // 可以扫出二维码的内容
        console.log(res)
        result = JSON.parse(result)
        // console.log(result)
        pageModel.scanMerchant({ order_id: result.id }).then(() => {

          this.setData({
            page: 0,
            pageSize: 10,
            list: [],
            busy: false,
          })
          this._getList()

          wx.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 1000
          })
        })
      },
      fail() {
        wx.showToast({
          title: '错误',
          icon: 'error',
          duration: 1000
        })
      }
    })
  },

  onLogout() {
    wx.removeStorage({
      key: 'merchant_id',
      success(res) {
        wx.switchTab({
          url: '/pages/center/index'
        })
      }
    })
  }


});
